package com.sunshine.litemusic.fragment.search;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author sunshine
 * @date 2020/5/28
 * 主活动的viewModel，主要负责数据的处理和储存
 */
public class SearchViewModel extends AndroidViewModel {

    private final static String TAG = "SearchViewModel";
    private MutableLiveData<ArrayList<SearchModel.SearchBean>> songBeanMutableLiveData;

    public SearchViewModel(@NonNull Application application) {
        super(application);
        songBeanMutableLiveData = new MutableLiveData<>();
        songBeanMutableLiveData.setValue(null);
    }

    MutableLiveData<ArrayList<SearchModel.SearchBean>> getSongBeanMutableLiveData() {
        return songBeanMutableLiveData;
    }

    void getMusic(){
        getMusic(497083385);
    }

    void getMusic(int id){
        String url = "https://api.imjad.cn/cloudmusic/?type=playlist&id=";
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url + id).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e(TAG, "onFailure");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                resolveMusicJSON(response.body().string());
                Log.e(TAG, "onResponse");
            }
        });
    }

    private void resolveMusicJSON(String html){
        try{
            JsonArray jsonArray = JsonParser
                    .parseString(html)
                    .getAsJsonObject()
                    .getAsJsonObject("playlist")
                    .getAsJsonArray("tracks");
            ArrayList<SearchModel.SearchBean> songBeanArrayList = new ArrayList<>();
            for (JsonElement jsonElement : jsonArray){
                SearchModel.SearchBean songBean = new Gson().fromJson(jsonElement, SearchModel.SearchBean.class);
                songBeanArrayList.add(songBean);
            }
            songBeanMutableLiveData.postValue(songBeanArrayList);   //这里不能用setValue因为它只能在主线程调用
        }catch (Exception e){
            Log.e(TAG, e.toString());
        }
    }
}
